package com.jrx.anytxn.transaction.job.payReminder.config;

import com.jrx.anytxn.param.entity.PrSmsSendingRules;
import com.jrx.anytxn.param.mapper.ext.ExtPrSmsSendingRulesMapper;
import com.jrx.anytxn.transaction.config.SmsMqConfig;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.service.ISmsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * 还款提醒短信任务
 *
 * @author lbz
 */
@Configuration
@EnableConfigurationProperties(SmsMqConfig.class)
public class PayReminderConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(PayReminderConfiguration.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Resource
    private ExtPrSmsSendingRulesMapper extPrSmsSendingRulesMapper;

    @Autowired
    private ISmsService iSmsService;

    @Autowired
    private SmsMqConfig smsMqConfig;

    @Bean
    public Job payReminderJob() {
        return jobBuilderFactory.get("payReminderJob")
                .start(payReminderStep())
                .build();
    }

    @Bean
    public Step payReminderStep() {
        return stepBuilderFactory.get("payReminderStep")
                .tasklet(payReminderTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet payReminderTasklet() {
        return (stepContribution, chunkContext) -> {
            logger.debug("还款提醒短信处理开始。。。。。。");
            Integer poolSize = smsMqConfig.getMaxPoolSize();
            List<PrSmsSendingRules> rulesList = extPrSmsSendingRulesMapper.selectBySmsType(Arrays.asList(TransBizConstant.SMS_TYPE_PAYREMINDER,TransBizConstant.SMS_TYPE_PAYMENT_REMINDER,
                    TransBizConstant.SMS_TYPE_BILL_PAY_REMINDER, TransBizConstant.SMS_TYPE_OVERDUE_REMINDER));
            if(!CollectionUtils.isEmpty(rulesList)){
                iSmsService.payReminderProcess(rulesList,poolSize);
            }
            logger.debug("还款提醒短信处理完成");
            return RepeatStatus.FINISHED;
        };
    }
}
